package com.travelplanning.admin.controller;

import cn.hutool.core.lang.UUID;
import com.travelplanning.admin.common.convention.Result;
import com.travelplanning.admin.common.convention.Results;
import com.travelplanning.admin.common.exception.ClientException;
import com.travelplanning.admin.util.AliOssUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Tag(name = "图片上传相关接口")
@RestController
@RequiredArgsConstructor
public class CommonController {

    private final AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "图片上传")
    public Result<String> upload(MultipartFile file){

        try{
            //获取原始文件名后缀
            String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //用uuid作为文件名，防止生成的临时文件重复
            String objectName = UUID.randomUUID().toString() + extension;
            //上传文件
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Results.success(filePath);
        } catch (MaxUploadSizeExceededException | IOException e) {
            if (e.toString().equals("MaxUploadSizeExceededException")){
                throw new ClientException("图片大小过大");
            }

        }
        return Results.failure("文件上传失败");
    }
}
